import sql


def get_relational_brainMap():
    brainMaps = [{"id": "root", "isroot": True, "topic": "中控系统"}]
    devices = sql.show_device()

    groups_name = sql.show_groups_name()
    gd = dict(groups_name)

    devices_name = sql.show_device_name()
    dd = dict(devices_name)

    i = 1
    for device in devices:
        topic = device[1]
        brainMap = {"id": str(i), "parentid": "root", "topic": topic, "direction": "right"}
        brainMaps.append(brainMap)
        connections = sql.show_connection_device(device[0])
        j = 1
        for connection in connections:
            if connection[2] == 'DEVICE':
                sub_name = dd[connection[3]]
                sub_brainMap = {"id": str(i) + str(j), "parentid": str(i), "topic": sub_name}
            elif connection[2] == 'GROUP':
                sub_name = gd[connection[4]]
                sub_brainMap = {"id": str(i) + str(j), "parentid": str(i), "topic": sub_name, "isLink": True}
                group_device = sql.show_group_device_ids(connection[4])
                group_device_ids = group_device[0][2].split(',')
                for k in range(len(group_device_ids)):
                    # group_device_id = group_device_ids[k]
                    children_name = dd[int(group_device_ids[k])]
                    children_brainMap = {"id": str(i) + str(j) + str(k), "parentid": str(i) + str(j),
                                         "topic": children_name}
                    brainMaps.append(children_brainMap)

            brainMaps.append(sub_brainMap)
            j += 1
        i += 1
    return brainMaps
